"""用户模块的 CRUD 封装

提供常用的数据访问操作，供路由层调用。
"""

from typing import Optional, Iterable

from sqlmodel import Session, select

from .model import User, UserRole


def get_by_username(session: Session, username: str) -> Optional[User]:
    return session.exec(select(User).where(User.username == username)).first()


def create_user(
    session: Session,
    username: str,
    hashed_password: str,
    full_name: Optional[str] = None,
    role: UserRole = UserRole.user,
) -> User:
    user = User(
        username=username,
        full_name=full_name,
        hashed_password=hashed_password,
        disabled=False,
        role=role,
    )
    session.add(user)
    session.commit()
    session.refresh(user)
    return user


def list_users(session: Session) -> Iterable[User]:
    return session.exec(select(User)).all()


def get_by_id(session: Session, user_id: int) -> Optional[User]:
    return session.get(User, user_id)


def set_password(session: Session, user: User, hashed_password: str) -> None:
    user.hashed_password = hashed_password
    session.add(user)
    session.commit()


def set_disabled(session: Session, user: User, disabled: bool) -> None:
    user.disabled = disabled
    session.add(user)
    session.commit()


def delete_user(session: Session, user: User) -> None:
    session.delete(user)
    session.commit()


